import * as actionTypes from "./actionTypes";
import { fromJS } from "immutable"; //把数据转为immutable对象，使用这个使用更要使用gget方法，使用set方法去变更state内容
 
const defaultState = fromJS({
  serchKey: "",
  serchKeyArr:   [],
  myColletList: [],
  collectNoverById:   [],
  collectNoverByIdList:   [],
  myColletListLen: 0,
  novelDetailsData: {},
});
// 导出一个纯函数
export default (state = defaultState, action) => {
  let collectNoverById = state.get('collectNoverById').toJS()  
  let collectNoverByIdList = state.get('collectNoverByIdList').toJS()    
  switch (action.type) {
    case actionTypes.DelHistory:
      let arr = []
      return state.merge(
        {
          serchKeyArr: fromJS(arr),
        }
      )
    case actionTypes.ChangeSearchList:
      let { serchKey, myColletList } = action.result;
      let serchKeyArr = state.get("serchKeyArr").toJS()
      serchKeyArr.push(serchKey);
      serchKeyArr = [...new Set([...serchKeyArr])];
      
      return state.merge(
        {
          serchKey,
          serchKeyArr: fromJS(serchKeyArr),
          myColletList: fromJS(myColletList.books),
        }
      )
    case actionTypes.ChangenovelDetailsData:
      return state.merge(
        {
          novelDetailsData: fromJS(action.result),
        }
      )
    case actionTypes.CollectNoverById:
      console.log(111111,collectNoverById ,action.id)
      collectNoverById.push(action.id);
      collectNoverById = [...new Set([...collectNoverById])];
     
      let addTemp = state.get("novelDetailsData").toJS()
      let cbidlist = collectNoverByIdList;
      cbidlist.push(addTemp);
      cbidlist = [...new Set([...cbidlist])];
    
      return state.merge(
        {
          collectNoverById: fromJS(collectNoverById),
          collectNoverByIdList: fromJS(cbidlist),
        }
      )
    case actionTypes.CollectNoverByIdList:
      
      return state.merge(
        {
          collectNoverByIdList: fromJS(action.result),
        }
      )
    case actionTypes.CollectNoverByIdDe:
      collectNoverById.splice(collectNoverById.findIndex(item => item === action.id), 1)
      collectNoverById = [...new Set([...collectNoverById])];
      
      // collectNoverByIdList.splice(collectNoverByIdList.findIndex(item =>  item._id === action.id), 1)  
      let cbidlists = collectNoverByIdList;
      for (let index = 0; index < cbidlists.length; index++) {
        const element = cbidlists[index];
        if (element._id === action.id) {
          cbidlists.splice(cbidlists.findIndex(item => item._id === action.id), 1)
          break
        }
      }
     
      return state.merge(
        {
          collectNoverById: fromJS(collectNoverById),
          collectNoverByIdList: fromJS(cbidlists),
        }
      )
    default:
      return state;
  }
};
